var DL = (function(){
	var userConfig;
	var dlTplFun,
		isFinding = false,
		isWaitStoping = false,
		rootDirEntry,
		regLi = /<li>.+?href="([^"]+)"[^>]*>([^<]+)</gi,
		regArticleDatetime = /<SPAN class=datetime>(.+?)<\/SPAN>/i,
		regArticleImage = /<div class=contentImage><IMG src="([^"]+)">(<BR><SPAN class=imagecaption>(.+?)<\/SPAN>)?/i,
		regMp3Url = /<a id="mp3" href="([^"]+)"/i,
		regLyricUrl = /<a id="lrc" href="([^"]+)"/i,
		regTranslationUrl = /<a id="EnPage" href="([^"]+)"/i,
		tempDlInfo = {},
		dlWaitList = [],
		curDlInfo;

	var xhr,
		fileTransfer;

	function rebuildList(){
		var html = '';
		for(var i=0,len=userConfig.list.length;i<len;i++){
			var cat = userConfig.list[i];
			if(tempDlInfo[cat].length<=0) continue;
			var nameArray = VoaStorage.getSongNameByCat(cat);
			for(var pos=tempDlInfo[cat].length-1;pos>=0;pos--){
				if(nameArray.indexOf(tempDlInfo[cat][pos].name)>=0)
					tempDlInfo[cat].splice(pos, 1);
			}
			if(tempDlInfo[cat].length<=0) continue;
			var data = {
				cat: cat,
				catName: Conf.title[cat],
				list: tempDlInfo[cat]
			};
			html += dlTplFun(data);
		}
		if(html)
			$('.dl-list-box').html(html);
		else{
			$('.dl-list-box').html('<h1>51Voa暂时没有更新内容，请稍后再试</h1>');
		}
		$('.dl-btn-find i').removeClass('dl-btn-find-anim');
	}
	function getUnload(index){
		index = index || 0;
		if(index>=userConfig.list.length){
			isFinding = false;
			rebuildList();
			return;
		}
		var cat = userConfig.list[index];
		tempDlInfo[cat] = [];
		var tempCat = tempDlInfo[cat];
		$.get(Conf.url[cat], function(text){
			text = text.split('<div id="list">');
			if(text.length<2)
				getUnload(++index);
			text = text[1].split('<div id="pagelist">')[0];
			text.replace(regLi, function(_$, _$1, _$2){
				if(tempCat.length >= userConfig.cacheCount) return;
				var hasLyric = false,
					hasTranslation = false;
				if(_$.indexOf('lrc.gif')>0) hasLyric=true;
				if(_$.indexOf('yi.gif')>0) hasTranslation = true;
				var name = _$2.trim();
				tempCat.push({
					id: util.uniqueId(),
					cat: cat,
					url:_$1, 
					name: name,
					nameEnc: name.encode4Html(),
					hasTranslation: hasTranslation,
					hasLyric: hasLyric
				});
			});

			getUnload(++index);
		});
	}
	function checkFolder(path){
		var def = new $.Deferred();
		rootDirEntry.getDirectory(path, {create: true}, function() {
			def.resolve();
		}, function(){
			def.reject();
		});
		return def;
	}
	function writeFile(filePath, text){
		var def = new $.Deferred();
		rootDirEntry.getFile(
			filePath, 
			{create: true, exclusive: false}, 
    		function(fileEntry){
				fileEntry.createWriter(function(writer){
					writer.onwriteend = function(){
						def.resolve();
					}
					writer.write(text);
				}, function(){
					console.error('createWriter faile');
					def.reject();
				});
			}, function(){
				console.error('get file fail');
				def.reject();
			}
		);

		return def;
	}
	function checkCatFolder(index){
		index = index || 0;
		if(index>=userConfig.list.length){
			tempDlInfo = {};
			getUnload();
			return;
		}

		var catName = userConfig.list[index];
		$.when(
			checkFolder('mp3/'+catName), 
			checkFolder('article/'+catName), 
			checkFolder('lyric/'+catName), 
			checkFolder('translation/'+catName),
			checkFolder('image/'+catName)
		).done(function(){
			index++;
			checkCatFolder(index);
		}).fail(function(){
			isFinding = false;
			console.error('create folder fail');
		})
	}
	function startFind(){
		if(isFinding) return;
		if(!util.isNetworkOk()){
			console.error('network unavailable');
			return;
		}
		if(userConfig.onlyWifi && navigator.connection.type!=Connection.WIFI){
			console.error('非wifi，不下载');
			return;
		}
		$('.dl-btn-find i').addClass('dl-btn-find-anim');

		isFinding = true;

		window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function(dirEntry) {
			dirEntry.getDirectory('51voa', {create: true}, function(_dirEntry) {
				rootDirEntry = _dirEntry;
				$.when(
					checkFolder('mp3'), 
					checkFolder('article'), 
					checkFolder('lyric'), 
					checkFolder('translation'),
					checkFolder('image')
				).done(function(){
					checkCatFolder();
				}).fail(function(){
					console.error('create type folder faile');
				});
			}, function(){
				console.error('目录找不到');
				isFinding = false;
			});
		}, function(error){
			console.error('文件路径有问题', 'error');
	        isFinding = false;
		});
	}

	function dlLog(text){
		$('#'+curDlInfo.id+" .dl-song-item-tip").html(text);
	}
	function dlFail(){
		dlLog('下载失败', 'fail');
		startDlWork();
	}
	function dlWorkFail(type){
		if(isWaitStoping){
			dlLog('已停止下载');
			isWaitStoping = false;
		}else
			dlFail('下载'+type+'失败');
		curDlInfo = null;
		setTimeout(startDlWork, 200);
	}
	function startDlWork(){
		if(curDlInfo) return;
		if(dlWaitList.length <=0){
			rebuildList();
			return;
		}
		curDlInfo = dlWaitList.shift();
		
		dlArticle().done(function(){
			dlTranslation().done(function(){
				dlLyric().done(function(){
					dlMp3().done(function(){
		            	VoaStorage.addSong({
		            		cat: curDlInfo.cat,
		            		name: curDlInfo.name,
		            		hasImg: curDlInfo.imgUrl ? true: false,
		            		imgDesc: curDlInfo.imgDesc || '',
		            		hasTranslation: curDlInfo.translationUrl ? true : false,
		            		hasLyric: curDlInfo.lyricUrl ? true: false,
		            		ctime: (new Date()).getTime()
		            	});
		            	dlLog('下载完成');
		            	$('#'+curDlInfo.id).removeClass('dl-song-item-wait').addClass('dl-song-item-done');
		            	curDlInfo = null;
		            	startDlWork();
					}).faile(function(){
						dlWorkFail('mp3');
					})
				}).faile(function(){
					dlWorkFail('字幕');
				});
			}).fail(function(){
				dlWorkFail('翻译');
			});
		}).fail(function(){
			dlWorkFail('原文');
		});
	}
	function dlArticle(){
		var def = new $.Deferred();
		dlLog('下载原文');
		var articleUrl = util.getAbsoluteUrl(curDlInfo.url);
		xhr = $.get(articleUrl).done(function(text){
			xhr = null;
			if(!regMp3Url.test(text)){
				def.reject();
				return;
			}
			curDlInfo.mp3Url = RegExp.$1;
			if(regLyricUrl.test(text)){
				curDlInfo.lyricUrl = util.getAbsoluteUrl(RegExp.$1.trim());
			}
			if(regTranslationUrl.test(text)){
				curDlInfo.translationUrl = RegExp.$1;
			}
			if(regArticleImage.test(text)){
				var imgUrl = RegExp.$1.trim();
				if(imgUrl)
					curDlInfo.imgUrl = imgUrl;
				var imgDesc = RegExp.$3.trim();
				if(imgDesc)
					curDlInfo.imgDesc = imgDesc;
			}

			if(regArticleDatetime.test(text)){
				curDlInfo.datetime = RegExp.$1;
			}

			text = text.split('<div id="content">')[1].split('<div id="Bottom_VOA">')[0];
			var article = '';
			text.replace(/<p>((.|\n)+)<\/p>/gi, function(_$, _$1){
				article += _$1.replace(/<\/?\w.*>/g,'')+'\n';
			});
			writeFile('article/'+curDlInfo.cat+'/'+curDlInfo.name+'.txt', article).done(function(){
				if(isWaitStoping){
					def.reject();
				}else
					def.resolve();
			}).fail(function(){
				def.reject();
			});
		}).fail(function(){
			xhr = null;
			def.reject();
		});
		return def;
	}
	function dlTranslation(articleUrl){
		var def = new $.Deferred();
		if(!curDlInfo.translationUrl){
			def.resolve();
			return;
		}
		dlLog('下载翻译');
		var relativePath = articleUrl.substring(0, articleUrl.lastIndexOf('/'));
		var transUrl = util.getAbsoluteUrl(curDlInfo.translationUrl, relativePath);
		xhr = $.get(transUrl).done(function(text){
			xhr = null;
			text = text.split('<div id="content">')[1].split('<div id="Bottom_VOA">')[0];
			var article = '';
			text.replace(/<p>((.|\n)+)<\/p>/gi, function(_$, _$1){
				article += _$1.replace(/<\/?\w.*>/g,'')+'\n';
			});
			writeFile('translation/'+curDlInfo.cat+'/'+curDlInfo.name+'.txt', article).done(function(){
				if(isWaitStoping){
					def.reject();
					return;
				}
				def.resolve();
			}).fail(function(){
				def.reject();
			});
		}).fail(function(){
			xhr = null;
			def.reject();
		});

		return def;
	}
	function dlLyric(){
		var def = new $.Deferred();
		if(!curDlInfo.lyricUrl){
			def.resolve();
			return;
		}
		dlLog('下载字幕');
		var lyricUrl = encodeURI(curDlInfo.lyricUrl);
		fileTransfer = new FileTransfer();
		fileTransfer.download(
            lyricUrl,
            cordova.file.externalRootDirectory + '51voa/lyric/'+curDlInfo.cat+'/'+curDlInfo.name+'.lrc',
            function() {
            	fileTransfer = null;
            	def.resolve();
            },
            function(error) {
            	fileTransfer = null;
            	def.reject();
            },
            false
        );
	}
	function dlMp3(){
		var def = new $.Deferred();
		dlLog('下载mp3');
		var mp3Uri = encodeURI(curDlInfo.mp3Url);
		fileTransfer = new FileTransfer();
		fileTransfer.onprogress = function(evt) {
			if(!evt.total) return;
			var percentage = (evt.loaded / evt.total*100).toFixed(1);
			$('#'+curDlInfo.id+' .dl-song-item-progress').css('width',percentage+'%');
			dlLog('下载mp3: '+util.formatSize(evt.loaded)+'/'+util.formatSize(evt.total)+', '+percentage+'%');
		};
		fileTransfer.download(
            mp3Uri,
            cordova.file.externalRootDirectory + '51voa/mp3/'+curDlInfo.cat+'/'+curDlInfo.name+'.mp3',
            function() {
            	fileTransfer = null;
            	def.resolve();
            },
            function(error) {
            	fileTransfer = null;
            	def.reject();
            },
            false
        );
	}
	function addDlWork(cat, index){
		if(curDlInfo && curDlInfo.name==tempDlInfo[cat][index].name)
			return;
		if(dlWaitList.indexOf(tempDlInfo[cat][index])>=0)
			return;
		dlWaitList.push(tempDlInfo[cat][index]);
		startDlWork();
	}
	function removeWork(cat, index){
		var index = dlWaitList.indexOf(tempDlInfo[cat][index]);

		if(index>=0){
			dlWaitList.splice(index, 1);
		}else{
			if(xhr){
				xhr.abort();
			}
			else if(fileTransfer){
				fileTransfer.abort();
			}
			else{
				isWaitStoping = true;
			}
		}
	}
	function clearDlWork(){}
	function init(){
		userConfig = VoaStorage.getUserConfig();
		dlTplFun = $('#dlTpl').html().tmpl();
		$('.dl-btn-find').tap(startFind);
		$('.dl-list-box').delegate('.dl-song-btn', 'tap', function(){
			var btn = $(this).removeClass('dl-song-btn');
			var item = $(this).parents('.dl-song-item').addClass('dl-song-item-wait');
			var cat = item.data('cat');
			var index = parseInt(item.data('index'));

			addDlWork(cat, index);

			setTimeout(function(){
				btn.addClass('dl-wait-btn');
			},1);
		});
		$('.dl-list-box').delegate('.dl-wait-btn', 'tap', function(){
			var btn = $(this).removeClass('dl-wait-btn');
			var item = $(this).parents('.dl-song-item');
			var cat = item.data('cat');
			var index = parseInt(item.data('index'));
			removeWork(cat, index);
		});
	}

	return{
		init: init
	}
})();